package com.yhh.gateway.filter;

import com.yhh.common.base.ret.ApiResult;
import com.yhh.common.jwt.JWTUtil;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关过滤器
 * 登录鉴权
 */
@Component
public class AuthLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // url 过滤 注册、登录、SwaggerUI洁面不需要token 鉴权
        String path = request.getURI().getPath();
        if(path.contains("member/api/v1")|| path.contains("v2/api-docs")){
            return chain.filter(exchange);
        }
        // 获取token
        String token = request.getHeaders().getFirst("TOKEN");
        ServerHttpResponse response = exchange.getResponse();
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 解析token
        ApiResult ret = JWTUtil.verifyToken(token);
        if(ret.getCode() != ApiResult.SUCCESS_CODE){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 验证通过
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
